Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

193
Vistas
Socket io, Try multiple URLs to establish connection after "connect_error"

I have an app with divided code (client / server). On the client side, I'd like socket io to attempt multiple URLs (one at a time) until it connects successfully.

Here's my code:

const BAD_HOST = "http://localhost:8081";
const LOCAL_HOST = "http://localhost:8080";
const SOCKET_CONFIG = {
  upgrade: false,
  transports: ["websocket"],
  auth: { ... }, // Trimmed for brevity
  extraHeaders: { ... }, // Trimmed for brevity
};

let socket = io(BAD_HOST, SOCKET_CONFIG); // This connects fine when I use LOCAL_HOST

socket.on("connect_error", (err) => {
  console.log(err); 
  socket = io(LOCAL_HOST, SOCKET_CONFIG); // DOES NOT WORK
});

socket.on("connect", () => { ... } // Trimmed for brevity

In short, when I try to reassign the value for socket to a new io connection, it seems to retain the old, failed connection. My browser continues to throw 'connect_error' messages from the bad url: WebSocket connection to 'ws://localhost:8081/socket.io/?EIO=4&transport=websocket' failed:

I checked but couldn't find any official documentation on this question.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

I think an approach is already discussed here: https://stackoverflow.com/a/22722710/656708

Essentially you have an array of URLs, which in your case would be:

const socketServerURLs = ["http://localhost:8081","http://localhost:8080"];

and then iterate over them, trying to initiate a socket connection, like this:

// something along these lines
socketServerURLs.forEach((url) => { 
  // ...
  socket.connect(url, socketConfiguration, (client) => {});
  // ...
}

Then again, I don't know what a BAD_HOST entails. Assuming that you mean that a connection to that host failed, how would you know that without actually trying to connect to it?

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda